<?php
namespace App\Service\Chat;

use App\Constants\Chat\RedisKey;
use App\Foundation\Traits\Singleton;
use App\Model\Chat\ChatFriend;
use App\Model\Chat\GroupRelation;
use App\Pool\Redis;
use App\Service\BaseService;

/**
 * 好友消息服务类
 */
class FriendService extends BaseService
{
    use Singleton;

    /**
     * 获取好友列表
     * @param $user_id
     * @return array|mixed|string
     */
    public  function getUserFriends($user_id)
    {
        $key = RedisKey::USER_FRIENDS_KEY . ':' . $user_id;
        $redis = Redis::getInstance();
        $cache = $redis->get($key);
        if ($cache) {
            return unserialize($cache);
        }
        $cache = ChatFriend::query()->select('*')->where([
            'user_id' => $user_id])->get()->toArray();
        $cache = array_column($cache, null, 'friend_id');
        $redis->set($key, serialize($cache));
        return $cache;
    }

    /**
     * 获取好友信息
     * @param $user_id
     * @param $friend_id
     * @return false
     */
    public function getFriend($user_id,$friend_id){
        $friends = FriendService::getInstance()->getUserFriends($user_id);
        if(!isset($friends[$friend_id])){
            return false;
        }
        return $friends[$friend_id];
    }


}
